package cn.com.dashihui.web.controller;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.jfinal.aop.Duang;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;

import cn.com.dashihui.kit.CommonKit;
import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.kit.ExcelExportUtil.Pair;
import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.AdSeller;
import cn.com.dashihui.web.dao.GSR;
import cn.com.dashihui.web.dao.Seller;
import cn.com.dashihui.web.dao.Store;
import cn.com.dashihui.web.dao.SysConfig;
import cn.com.dashihui.web.dao.User;
import cn.com.dashihui.web.service.SellerService;

public class SellerController extends BaseController{
	private SellerService sellerService = Duang.duang(SellerService.class);
	  public void index(){
	        render("index.jsp");
	    }
		/**
		 * 获得公司列表数据
		 */
		public void page(){
			int pageNum = getParaToInt(0, 1);
			int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
			//公司编号
			String sellerId = getPara("sellerId");
			//入驻范围
			String beginDate = getPara("beginDate");
			String endDate = getPara("endDate");
			//状态
			int state = getParaToInt("state",0);
			//公司电话
			String tel = getPara("tel");
			renderResult(0,sellerService.findByPage(pageNum,pageSize,sellerId,beginDate,endDate,state,tel));
		}
	   
	    /**
	     * 查看公司详情
	     */
	    public void detail(){
	    	String sellerId=getPara("sellerId");
			if(sellerId!=null){
				setAttr("object", sellerService.detail(sellerId));
			}
			render("detail.jsp");
	    }
	    
	    /**
	     * 降权toDrop
	     */
	    public void toDrop(){
	    	String sellerId=getPara("sellerId");
	    	
	    	if(StrKit.isBlank(sellerId)){
				renderFailed("参数sellerId不能为空");
	    		return;
	    	}else{
	    		setAttr("sellerId", sellerId);
	    		render("doDrop.jsp"); 
	    	}
	    }
	    /**
	     * 降权doDrop
	     */
	    public void doDrop(){
	    	String sellerId=getPara("sellerId");
	    	String reason=getPara("reason");
	    	String checktime=DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
	    	if(StrKit.isBlank(sellerId)){
				renderFailed("参数sellerId不能为空");
	    		return;
	    	}else{
	    		int i= sellerService.doDrop(reason,sellerId,checktime);
	    		if(i==1){
	    			renderSuccess(sellerService.findPageBySellerId(sellerId));
	    			return ;
	    		}else{
	    			//3.其他情况
					renderFailed("驳回失败");
					return;
	    		}
	    	}
	    }
	     /**
	     * 打开驳回toCancel页面
	     */
	    public void toCancel(){
	    	String sellerId=getPara("sellerId");
	    	if(StrKit.isBlank(sellerId)){
				renderFailed("参数sellerId不能为空");
	    		return;
	    	}else{
	    		setAttr("sellerId", sellerId);
	    		render("doCancel.jsp"); 
	    	}
	    }
	    /**
	     * 驳回doCancel
	     */
	    public void doCancel(){
	    	String sellerId=getPara("sellerId");
	    	String reason=getPara("reason");
	    	String checktime=DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
	    	if(StrKit.isBlank(sellerId)){
				renderFailed("参数sellerId不能为空");
	    		return;
	    	}else{
	    		int i= sellerService.doCancel(reason,sellerId,checktime);
	    		if(i==1){
	    			renderSuccess(sellerService.findPageBySellerId(sellerId));
	    			return ;
	    		}else{
	    			//3.其他情况
					renderFailed("驳回失败");
					return;
	    		}
	    	}
	    }
	    /**
	     * 通过审核
	     */
	    public void doAccept(){
	    	String sellerId=getPara("sellerId");
	    	String checktime=DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
	    	if(StrKit.isBlank(sellerId)){
				renderFailed("参数sellerId不能为空");
	    		return;
	    	}
			//获取当前的seller
			Seller seller = sellerService.findBySellerId(sellerId);
			//获取所属公司ID
			
			//电话
			String aphone = seller.get("contact");
			//通过电话号码查询当前用户对象，即验证是否存在账号
			User userNew = sellerService.findUserByPhone(aphone);
			//设置用户密码，默认为手机号后六位
			String password = aphone.substring(aphone.length() - 6);
			//验证seller的状态如果是5则直接修改seller信息
			int sState = seller.get("state");
			if (sState==6) {
				seller.set("checktime", checktime).set("state", 2).update();
				renderSuccess();
			}else{
			if (userNew!=null) {
				
				//此手机号已存在，无法审核
				renderResult(1);
				return;
			} else {
				//审核通过
				int seid = seller.get("id");
				int adminid = seller.getInt("userid");
				AdSeller adSeller = sellerService.findSeller(adminid);
				
	    		seller.set("checktime", checktime).set("state", 2);
				User user2 = new User();
				String date= DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
				//所属分公司
    			String aname = seller.get("legalPerson");
    			//会员状态
    			int state =1;
    			//给公司添加会员
    			String address  = "请修改您的地址";
    			String cards=DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS");
    			String card=cards.substring(2);
				user2.set("name", aname)
					.set("card", card)
				 	.set("phone", aphone)
				 	.set("state", state)
				 	.set("address", address)
				 	.set("createDate", date)
				 	.set("toBossThreeId", seid)//公司账户所属公司为其本身，既t_bus_seller的id
				 	.set("babythday",DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
				 	.set("taici", SysConfig.tBusUserTaici.level_7)
				 	.set("userType", 1)//设置客户类型为法人
				 	.set("password", CommonKit.encryptPassword(password));//设置用户密码，默认为手机号后六位
				//事务
				boolean flag = Db.tx(new IAtom() {
			           @Override
			           public boolean run() throws SQLException {
			            return seller.update()&&user2.save();
			           }
			          });
				 if (flag) {
					 int tokerid = user2.get("id");
					 seller.set("tokerUserid", tokerid);
					 adSeller.set("tokerUserid", tokerid);
					//事务
					boolean flag1 = Db.tx(new IAtom() {
						@Override
						public boolean run() throws SQLException {
							return adSeller.update()&&seller.update();
						}
					});
					 if (flag1) {
						renderSuccess();
					}
				} else {
					logger.error("前端用户添加失败！");
				}
			}
		}
		renderSuccess(sellerService.findPageBySellerId(sellerId));
		return ;
    }
	 
	    /**
	     * 删除商户
	     */
	    public void doDelete(){
	    	String sellerId=getPara("sellerId");
	    	if(StrKit.isBlank(sellerId)){
				renderFailed("参数sellerId不能为空");
	    		return;
	    	}else{
	    		Seller seller=sellerService.findBySellerId(sellerId);
	    		AdSeller adse=sellerService.findSeller(seller.getInt("userid"));
	    			//删除公司下的分公司
	    			List<Store> storeList=sellerService.findStoreBySeller(sellerId);
	    			if(storeList.size()>0){
	    				for (Store store : storeList) {
	    					List<GSR> dsr=sellerService.finds(store.get("storeid"));
	    					//判断是否有未下架商品，有关联商品不允许删除
	    					if(dsr.size()>0){
	    						renderResult(2);
	    						return;
	    						/*for (GSR gsr : dsr) {
	    							//删除商品关联
	    							gsr.delete();
								}*/
	    					}
	    					//删除营业部
	    					store.delete();
	    				}
	    			}
	    			//删除公司以及后台用户
	    		if(seller.delete() && adse.delete()){
	    			renderSuccess();
	    			return ;
	    		}else{
	    			//3.其他情况
					renderFailed("删除失败");
					return;
	    		}
	    	}
	    }
	    /**
		 * excel导出
		 */
		public void doExcel(){
			List<Pair> titles = new ArrayList<Pair>();
		    titles.add(new Pair("sellerId", "公司ID"));
		    titles.add(new Pair("sellerName", "公司名称"));
		    titles.add(new Pair("createtime", "入住时间"));
		    titles.add(new Pair("trueName", "公司联系人"));
		    titles.add(new Pair("contact", "联系电话"));
		    titles.add(new Pair("state", "状态"));
		    titles.add(new Pair("checktime", "入住审核时间"));
			String sellerId = getPara("sellerId");
			String beginDate = getPara("beginDate");
			String endDate = getPara("endDate");
			int state = getParaToInt("state",0);
			String tel = getPara("tel");
			List<Record> list=sellerService.findExcelByPage(sellerId,beginDate,endDate,state,tel);
			List<Record> listz=new ArrayList<Record>();
			for (int i = 0; i < list.size(); i++) {
				Record record=new Record();
					record.set("sellerId",list.get(i).get("sellerId"));
					record.set("sellerName", list.get(i).get("sellerName"));
					record.set("createtime", list.get(i).get("createtime"));
					record.set("trueName", list.get(i).get("trueName"));
					record.set("contact", list.get(i).get("contact"));
					if(list.get(i).get("state").equals(1)){
						record.set("state", "入驻审核中");
					}else if(list.get(i).get("state").equals(2)){
						record.set("state", "入驻");
					}
					record.set("checktime", list.get(i).get("checktime"));
				listz.add(record);
	 		}
			// 导出
			sellerService.export(getResponse(), getRequest(),titles, listz);		
			renderNull();
		}
	/**
	 * 下架公司
	 */
	public void doDown() {
		String sellerId=getPara("sellerId");
		String downtime = DatetimeKit.getFormatDate("yyyy-MM-dd-hh-mm");
		if (StrKit.isBlank(sellerId)) {
			renderFailed("商家编码不能为空");
			return;
		}else{
			List<Store> liStores = sellerService.findStoreBySeller(sellerId);
			if (liStores!=null&&liStores.size()>0) {
				for (Store store:liStores) {
					
					List<GSR> listGSR = sellerService.finds(store.get("storeid"));
					if (listGSR!=null&&listGSR.size()>0) {
						for (GSR gsr : listGSR) {
							String goodstore = gsr.get("goodstore");
							//下线对应的分公司下的商品
							sellerService.downGoods(goodstore);
						}
					}
					//下线对应的分公司
					sellerService.downStore(store.get("storeid"));
				}
			}
			//下线公司
			sellerService.doDown(downtime,sellerId);
			renderSuccess();
			return;
		}
	}
}
